﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;

namespace OPCService.Utils
{
    public enum ToastType
    {
        Success,
        Warning,
        Error,
        Info
    }

    public static class ToastMessage
    {
        public static void Show(Form owner, string message, ToastType type = ToastType.Info, int displayTime = 3000)
        {
            var toast = new CustomMessageBox(owner, message, type, displayTime);
            toast.Show();
        }
    }

    internal class CustomMessageBox : Form
    {
        private readonly Form _owner;
        private Timer _closeTimer;
        private readonly int _displayTime;
        private readonly ToastType _type;
        private const int ANIMATION_STEP = 15;
        private const int MARGIN = 10;
        private Point _targetLocation;

        public CustomMessageBox(Form owner, string message, ToastType type, int displayTime)
        {
            _owner = owner;
            _displayTime = displayTime;
            _type = type;

            InitializeForm(message);
            InitializeComponents(message);
            InitializeTimer();

            // 绑定主窗体事件
            owner.LocationChanged += (s, e) => CalculatePosition();
            owner.SizeChanged += (s, e) => CalculatePosition();
            owner.FormClosing += (s, e) => Close();
        }

        private void InitializeForm(string message)
        {
            FormBorderStyle = FormBorderStyle.None;
            ShowInTaskbar = false;
            StartPosition = FormStartPosition.Manual;
            CalculatePosition();

            // 设置初始位置在窗体下方（不可见区域）
            Location = new Point(_targetLocation.X, _owner.Bottom);

            // 根据消息类型设置背景色 (兼容C# 7.3的方式)
            BackColor = GetColorForType();
            ForeColor = Color.White;
            Padding = new Padding(15);

            // 设置合适的大小
            using (var g = CreateGraphics())
            {
                SizeF textSize = g.MeasureString(message, Font);
                int width = (int)Math.Min(400, Math.Max(200, textSize.Width + 50));
                int height = (int)Math.Max(80, textSize.Height + 60);
                Size = new Size(width, height);
            }

            // 重新计算目标位置（尺寸变化后）
            CalculatePosition();
        }

        // 使用传统switch代替模式匹配
        private Color GetColorForType()
        {
            switch (_type)
            {
                case ToastType.Success:
                    return Color.FromArgb(103, 194, 58);   // 绿色
                case ToastType.Warning:
                    return Color.FromArgb(230, 162, 60);   // 橙色
                case ToastType.Error:
                    return Color.FromArgb(245, 108, 108);   // 红色
                case ToastType.Info:
                    return Color.FromArgb(64, 158, 255);  // 蓝色
                default:
                    return SystemColors.Control;
            }
        }

        private void CalculatePosition()
        {
            if (_owner == null || _owner.IsDisposed) return;

            // 计算右下角目标位置
            _targetLocation = new Point(
                _owner.Left + _owner.Width - Width - MARGIN,
                _owner.Top + _owner.Height - Height - MARGIN
            );

            // 确保不会超出屏幕边界
            Rectangle screenBounds = Screen.FromControl(_owner).WorkingArea;
            _targetLocation = new Point(
                Math.Max(screenBounds.Left, Math.Min(_targetLocation.X, screenBounds.Right - Width)),
                Math.Max(screenBounds.Top, Math.Min(_targetLocation.Y, screenBounds.Bottom - Height))
            );
        }

        private void InitializeComponents(string message)
        {
            // 图标（根据类型显示不同图标）
            var icon = new PictureBox
            {
                Size = new Size(32, 32),
                Location = new Point(15, (Height - 32) / 2),
                SizeMode = PictureBoxSizeMode.Zoom
            };

            // 传统switch代替模式匹配
            switch (_type)
            {
                case ToastType.Success:
                    icon.Image = Image.FromFile("Resource/chenggong.png"); //SystemIcons.Shield.ToBitmap();
                    break;
                case ToastType.Warning:
                    icon.Image = SystemIcons.Warning.ToBitmap();
                    break;
                case ToastType.Error:
                    icon.Image = Image.FromFile("Resource/error.png");  //SystemIcons.Error.ToBitmap();
                    break;
                case ToastType.Info:
                    icon.Image = SystemIcons.Information.ToBitmap();
                    break;
                default:
                    icon.Image = SystemIcons.Application.ToBitmap();
                    break;
            }

            // 消息文本
            var messageLabel = new Label
            {
                Text = message,
                Location = new Point(60, 15),
                Size = new Size(Width - 75, Height - 30),
                TextAlign = ContentAlignment.MiddleLeft,
                Font = new Font("Segoe UI", 9.5f),
                ForeColor = Color.White,
                BackColor = Color.Transparent
            };

            // 关闭按钮
            var closeButton = new Label
            {
                Text = "×",
                Font = new Font("Segoe UI", 12f, FontStyle.Bold),
                Size = new Size(24, 24),
                Location = new Point(Width - 30, 5),
                TextAlign = ContentAlignment.MiddleCenter,
                Cursor = Cursors.Hand,
                ForeColor = Color.White,
                BackColor = Color.Transparent
            };
            closeButton.Click += (s, e) => CloseWithAnimation();

            // 添加控件
            Controls.Add(icon);
            Controls.Add(messageLabel);
            Controls.Add(closeButton);

            // 确保关闭按钮可见
            closeButton.BringToFront();
        }

        private void InitializeTimer()
        {
            _closeTimer = new Timer();
            _closeTimer.Interval = _displayTime;
            _closeTimer.Tick += (s, e) => CloseWithAnimation();
            _closeTimer.Start();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            // 开始显示动画（从下方滑动到目标位置）
            var showTimer = new Timer { Interval = ANIMATION_STEP };
            int startY = Location.Y;

            showTimer.Tick += (s, evt) =>
            {
                // 使用线性插值实现平滑动画
                int newY = Location.Y - Math.Max(1, (Location.Y - _targetLocation.Y) / 5);
                Location = new Point(_targetLocation.X, newY);

                // 检查是否到达目标位置
                if (Math.Abs(newY - _targetLocation.Y) < 2)
                {
                    Location = new Point(_targetLocation.X, _targetLocation.Y);
                    showTimer.Stop();
                    showTimer.Dispose();
                }
            };

            showTimer.Start();
        }

        private void CloseWithAnimation()
        {
            // 停止自动关闭计时器
            if (_closeTimer != null)
            {
                _closeTimer.Stop();
                _closeTimer.Dispose();
            }

            // 开始关闭动画（向下滑动消失）
            var closeTimer = new Timer { Interval = ANIMATION_STEP };
            int targetY = _owner.Bottom;

            closeTimer.Tick += (s, e) =>
            {
                int newY = Location.Y + Math.Max(1, (targetY - Location.Y) / 5);
                Location = new Point(Location.X, newY);

                // 检查是否完全隐藏
                if (Location.Y >= _owner.Bottom - 10)
                {
                    closeTimer.Stop();
                    closeTimer.Dispose();
                    Close();
                    Dispose();
                }
            };

            closeTimer.Start();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // 绘制边框
            using (var borderPen = new Pen(Color.FromArgb(80, 80, 80), 1))
            {
                //e.Graphics.DrawRectangle(borderPen, 0, 0, Width - 1, Height - 1);
            }
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);
            CloseWithAnimation(); // 点击消息框任意位置立即关闭
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // 清理托管资源
                if (_closeTimer != null)
                {
                    _closeTimer.Dispose();
                }
            }
            base.Dispose(disposing);
        }
    }
}
